package com.base.server.common.config.jwt;

import com.base.server.common.config.RedisClient;
import com.base.server.common.constant.Constant;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Set;

/**
 * 描述：重写 shiro的 Cache保存读取
 * <p>
 * 作者：HuTongFu
 * 时间：2019/7/11 11:12
 */
public class CustomCache<k, V> implements Cache<k, V> {

    private int shiroCacheExpireTime = 28800;

    @Resource
    private RedisClient redis;

    /**
     * 缓存的key名称获取为shiro:cache:account
     *
     * @param key
     * @return java.lang.String
     */
    private String getKey(Object key) {
        return Constant.RedisConstant.PREFIX_TOKEN_U_CACHE+ JwtUtil.getClaim(key.toString(), Constant.JWT.ACCOUNT);
    }

    /**
     * 获取缓存
     */
    @Override
    public Object get(Object key) throws CacheException {
        if (!redis.hasKey(this.getKey(key))) {
            return null;
        }
        return redis.get(this.getKey(key));
    }

    /**
     * 保存缓存
     */
    @Override
    public Object put(Object key, Object value) throws CacheException {
        // 设置Redis的Shiro缓存
        return redis.set(this.getKey(key), value, shiroCacheExpireTime);
    }

    /**
     * 移除缓存
     */
    @Override
    public Object remove(Object key) throws CacheException {
        if (!redis.hasKey(this.getKey(key))) {
            return null;
        }
        redis.del(this.getKey(key));
        return null;
    }

    /**
     * 清空所有缓存
     */
    @Override
    public void clear() throws CacheException {
        // TODO Auto-generated method stub

    }

    /**
     * 缓存的个数
     */
    @Override
    public Set<k> keys() {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 获取所有的key
     */
    @Override
    public int size() {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * 获取所有的value
     */
    @Override
    public Collection<V> values() {
        // TODO Auto-generated method stub
        return null;
    }

}
